<?php

/**
 * This is the model class for table "message".
 *
 * The followings are the available columns in table 'message':
 * @property integer $id
 * @property integer $idseliste_em
 * @property string $sujet
 * @property string $message
 * @property string $date
 * @property integer $iddemande
 * @property integer $idoffre
 * @property integer $auto
 * @property integer $idmessage
 * @property integer $del_em
 *
 * The followings are the available model relations:
 * @property Message $idmessage0
 * @property Message[] $messages
 * @property Seliste $idselisteEm
 * @property Demande $iddemande0
 * @property Offre $idoffre0
 */
class Message extends CActiveRecord
{
	public $destinataire;
	
	public function init() {
		$this->destinataire = new Destinataire();
	}
	
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'message';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('idseliste_em, sujet, message, date', 'required'),
			array('idseliste_em, iddemande, idoffre, auto, idmessage, del_em', 'numerical', 'integerOnly'=>true),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, idseliste_em, sujet, message, date, iddemande, idoffre, auto, idmessage, del_em', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'idmessage0' => array(self::BELONGS_TO, 'Message', 'idmessage'),
			'messages' => array(self::HAS_MANY, 'Message', 'idmessage'),
			'selistes' => array(self::MANY_MANY, 'Seliste', 'destinataire(idmessage, idseliste)'),
			'idselisteEm' => array(self::BELONGS_TO, 'Seliste', 'idseliste_em'),
			'iddemande0' => array(self::BELONGS_TO, 'Demande', 'iddemande'),
			'idoffre0' => array(self::BELONGS_TO, 'Offre', 'idoffre'),
			'destinataires'=> array(self::HAS_MANY, 'Destinataire', 'idmessage'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'Numéro',
			'idseliste_em' => 'Expéditeur',
			'sujet' => 'Sujet',
			'message' => 'Message',
			'date' => 'Date',
			'iddemande' => 'Concerne la demande',
			'idoffre' => 'Concerne l\'offre',
			'auto' => 'Message automatique',
			'idmessage' => 'En réponse à',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('idseliste_em',$this->idseliste_em);
		$criteria->compare('sujet',$this->sujet,true);
		$criteria->compare('message',$this->message,true);
		$criteria->compare('date',$this->date,true);
		$criteria->compare('iddemande',$this->iddemande);
		$criteria->compare('idoffre',$this->idoffre);
		$criteria->compare('auto',$this->auto);
		$criteria->compare('idmessage',$this->idmessage);
		$criteria->compare('del_em',$this->del_em);
		if ($this->destinataire->idseliste>0) $criteria->compare('idseliste',$this->destinataire->idseliste);
		if ($this->destinataire->del_rec>0) $criteria->compare('del_rec',$this->destinataire->del_rec);
		
		$criteria->with = array('destinataires'=>array('together'=>true));
		
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	public function displayDestinataires($destinataires) {
		$d=0;
		$retour = "";
		foreach ($destinataires as $dest) {
			$d++;
			$retour .= $dest->idseliste0->pseudo;
			if ($d<count($destinataires)) $retour .= ", ";
		}
		return $retour;
	}
	
	/************************************************************************************/
	/* envoi de message :  																*/
	/* - via la messagerie interne pour tous les destinataires 							*/
	/* - via email pour ceux qui ont choisi la notification des messages / des demandes */
	/* - via email pour ceux qui ont choisi ce mode de contact							*/
	/************************************************************************************/
	public static function send_message($type,$id,$idfrom,$recipients) {
		// recherche de l'administrateur
		//$admin = Seliste::model()->findByPk(Yii::app()->params['global_admin']);
		// recherche de l'expéditeur
		$seliste_exp = Seliste::model()->findByPk($idfrom);
		$recipients_mail = array();
		$sujet_mail = "";
		$message_mail = "";
		
		switch ($type) {
			
			CASE "newgrain" : 	$message = new Message();
								$message->idseliste_em = $idfrom;
								$message->sujet = "Nouveau grain";
								$sujet_mail = "[Selavenir] - " . $message->sujet;
								$lien = CHtml::link("cliquant ici",array("grain/valider","id"=>$id));
								$message->message = "Le séliste " . $seliste_exp->pseudo . " a ajouté un grain. La validation d'un administrateur est requise, vous pouvez l'effectuer en " . $lien . ".";
								$lien = CHtml::link("cliquant ici",Yii::app()->createAbsoluteUrl("grain/valider",array("id"=>$id)));
								$message_mail = "Le séliste " . $seliste_exp->pseudo . " a ajouté un grain. La validation d'un administrateur est requise, vous pouvez l'effectuer en " . $lien . ".";
								$message->auto = 1;
								$message->date = date('Y-m-d H:i:s');
								$message->iddemande = $id;
								if ($message->save()) {
									foreach ($recipients as $recipient) {
										$dest = new Destinataire();
										$dest->idseliste = $recipient["id"];
										$dest->idmessage = $message->id;
										$dest->save();
										// email éventuel
										if ($recipient["notif_message"] == 1) $recipients_mail[] = $recipient;
									}
								}
								break;
								
			CASE "demande" : 	$message = new Message();
								$message->idseliste_em = $idfrom;
								$message->sujet = "Nouvelle demande";
								$sujet_mail = "[Selavenir] - " . $message->sujet;
								$message->message = "Le séliste " . $seliste_exp->pseudo . " a besoin de vous ! Une demande vous concernant a été faite, vous pouvez la consulter en cliquant sur la demande ci-dessus.";
								$lien = CHtml::link("cliquant ici",Yii::app()->createAbsoluteUrl("demande/view",array("id"=>$id)));
								$message_mail = "Le séliste " . $seliste_exp->pseudo . " a besoin de vous ! Une demande vous concernant a été faite, vous pouvez la consulter en ". $lien . ".";
								$message->auto = 1;
								$message->date = date('Y-m-d H:i:s');
								$message->iddemande = $id;
								if ($message->save()) {
									foreach ($recipients as $recipient) {
										$dest = new Destinataire();
										$dest->idseliste = $recipient["id"];
										$dest->idmessage = $message->id;
										$dest->save();
										// email éventuel
										if ($recipient["notif_demande"] == 1) $recipients_mail[] = $recipient;
									}
								}
								break;
								
			CASE "message" : 	foreach ($recipients as $recipient) {
									$dest = new Destinataire();
									$dest->idseliste = $recipient["id"];
									$dest->idmessage = $id;
									$dest->save();
									// email éventuel
									if ($recipient["notif_demande"] == 1) $recipients_mail[] = $recipient;
								}
								if (count($recipients_mail)>0) {
									$message = Message::model()->findByPk($id);
									$sujet_mail = "[Selavenir] - Nouveau message de " . $seliste_exp->pseudo;
									$lien = CHtml::link("cliquant ici",Yii::app()->createAbsoluteUrl("seliste/mail",array("id"=>$id)));
									$message_mail = "Le séliste " . $seliste_exp->pseudo . " vous a envoyé un message, vous pouvez le consulter en ". $lien . ".";
								}
								break;
			
		}
		
		// envoi des emails
		if (count($recipients_mail)>0) {
			self::send_mail($sujet_mail,$message_mail,$recipients_mail);
		}
		
	}
	
	/********************************/
	/* envoi de message par email	*/
	/********************************/
	public static function send_mail($sujet,$message,$recipients) {
		if (count($recipients)==0) return;
		$mail = new YiiMailer();
		$mail->setFrom(Yii::app()->params['adminEmail'], Yii::app()->params['adminNom']);
		$dests = array();
		foreach ($recipients as $recipient) {
			$dest[] = $recipient['email'];
		} 
		$mail->setTo($dest);
		$mail->setSubject($sujet);
		$mail->setBody($message);
		$mail->send();
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Message the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
}
